﻿using ManYan.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ManYan.Domain.Model.Entity;
using ManYan.Common.jwt;

namespace ManYan.Application.Admin
{
    public class AdminAppService : IAdminAppService
    {
        private readonly IBaseAppService<Users> _baseAppService;

        public AdminAppService(IBaseAppService<Users> baseAppService)
        {
            _baseAppService = baseAppService;
        }
        /// <summary>
        /// 后台用户登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <returns></returns>
        public Res AdminLogin(string userName, string userPwd)
        {


            if (userName == null)
            {
                throw new Exception("用户名不能为空");
            }
            if (userPwd == null)
            {
                throw new Exception("密码不能为空");
            }

            var user = _baseAppService.WhereLoadEntityT(x => x.UserName == userName && x.Password == userPwd);



            //  var user=  _wechatUserDomainService.WhereLoadEntity(x=>x.OpenId==dto.OpenId);
            if (user != null)
            {
                //如果成功，在后续拿到用户的角色，ID等相关数据
                Common.jwt.JwtHelper jwtHelper = new Common.jwt.JwtHelper();
                JwtSetting jwtSetting = new JwtSetting();
                string[] roles = new string[] { "管理员", "总裁" };
                jwtSetting.RoleId = String.Join(',', roles);
                jwtSetting.UserId = user.Id.ToString();
                jwtSetting.RemoteIP = String.Empty;
                jwtSetting.UserOrgId = "it";
                jwtSetting.UserNickName = user.UserName;
                string token = jwtHelper.CreateJwt(jwtSetting);
                string refresh_token = jwtHelper.CreateRefreshToken();//把refresh token写到数据库
               
                return new Res()
                {
                    Code = 200,
                    Msg = "登录成功",
                    Data = new
                    {
                        access_token = token,
                        refresh_token = refresh_token

                    }
                };
            }
            else
            {
                return new Res() { Code = 4001, Msg = "用户不存在", Data = null };
            }
        }


    }
}
